/*=============================================================================
#     FileName: AacEncoder.cpp
#         Desc: 
#       Author: zhfayuan
#        Email: afst2012@outlook.com
#      Version: 0.0.1
#   LastChange: 2020-10-12 22:29:32
#      History:
=============================================================================*/
#include <string.h>
#include <iomanip>
#include <iostream>
#include "AacDecoder.h"

AacDecoder::AacDecoder()
{
    _handle = aacDecoder_Open(TT_MP4_ADTS,1);
}

AacDecoder::~AacDecoder()
{
    if (_handle) {
        aacDecoder_Close(_handle);
        _handle = nullptr;
    }
}


void AacDecoder::decode(std::shared_ptr<std::vector<char>> &packet,std::function<void(std::shared_ptr<std::vector<char>>&,int32_t sample_rate,int32_t channel)> func)
{
    uint32_t  bytes;
    AAC_DECODER_ERROR err;
    size_t packet_size = packet->size();
    char * packet_data = packet->data();

    if( (packet_size <= 0)|| (nullptr == func) || (nullptr == _handle)) {
        return;
    }
    bytes = packet_size;

    do
    {
        aacDecoder_Fill(_handle,(UCHAR**)&packet_data,(UINT*)&packet_size,&bytes);
        err = aacDecoder_DecodeFrame(_handle,(INT_PCM*)_pcmBuffer,sizeof (_pcmBuffer),0);
        if(AAC_DEC_OK == err){
            auto info = aacDecoder_GetStreamInfo(_handle);
            std::shared_ptr<std::vector<char>> out;
            out = std::make_shared<std::vector<char>>();
            out->assign(_pcmBuffer,_pcmBuffer + info->frameSize * info->numChannels * 2);
            func(out,info->sampleRate,info->numChannels);
        }
    }  while(bytes>0);
}